﻿using Models.Common;
using Models.Device;
using Newtonsoft.Json;

using SqlSugar;
using System.Data;
using UtilsORM.MySqlData;
using Microsoft.EntityFrameworkCore;
using GatewayServerService.Data;
using UtilsORM;
using GatewayServerService.CloudCenter;

namespace GatewayServerService.CloudCenter
{
    public class ServiceCloudGateWay
    {
        /// <summary>
        /// 获取网关在线状态
        /// </summary>
        /// <param name="model_GateWay"></param>
        public void callBackGateWay(ModelGateway model_GateWay)
        {
            try
            {
                //因为首次使用网关设备是 不会知道cpu id，所以先配置已知code，来识别网关设备
                //iot_device_gateway表中gw_deviceid为空时，表示还没绑定网关设备

                Console.WriteLine("接收到边缘微服务器mq");
                string sql = "select *,(case when d_status is null then 1 else d_status end) dstatus from iot_device_gateway left join iot_device on d_guid=gw_d_guid where  gw_code='" + model_GateWay.gatewayCode + "'";
                DataTable dt = MySqlYihongIot.GetDataTable(sql);
                if (dt.Rows.Count > 0)
                {

                    if (dt.Rows[0]["gw_system_start_code"].ToString() != model_GateWay.systemStartCode)
                    {
                        //更新设备启动时间
                        model_GateWay.startTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                    }
                    else
                    {
                        model_GateWay.startTime = Convert.ToDateTime(dt.Rows[0]["gw_start_time"].ToString()).ToString("yyyy-MM-dd HH:mm:ss");

                    }


                    sql = "update  iot_device_gateway set gw_deviceid='" + model_GateWay.gatewayDeviceId + "',gw_software_version='" + model_GateWay.versionNo + "',gw_local_ip='" + model_GateWay.localIp + "',gw_mac='" + model_GateWay.mac + "',gw_start_time='" + model_GateWay.startTime + "'," +
                        "gw_cpu_temperature=" + model_GateWay.cpuTemperature + " ," +
                        "gw_gpu_temperature=" + model_GateWay.gpuTemperature + " ," +
                        "gw_memory_total=" + model_GateWay.memoryTotal + " ," +
                        "gw_memory_use=" + model_GateWay.memoryUse + " ," +
                        "gw_memory_empty=" + model_GateWay.memoryEmpty + " ," +
                        "gw_system_start_code='" + model_GateWay.systemStartCode + "' ," +
                        "gw_live_time='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "' where  gw_code='" + model_GateWay.gatewayCode + "'  ";
                    MySqlYihongIot.ExecuteCommand(sql);



                    new ServiceCloudDeviceLiveState().setDeviceLiveState(dt.Rows[0]["d_guid"].ToString(), 1, "");

                    model_GateWay.gwGuid = dt.Rows[0]["gw_guid"].ToString();
                    model_GateWay.gatewayDeviceGuid = dt.Rows[0]["gw_d_guid"].ToString();
                    //向网关推送时间
                    new ServiceCloudGateWay_Init().sendTimeToGateWay(model_GateWay);

                    //异步 ///初始化设备
                    resetMichine(dt, model_GateWay);
                }
                else
                {
                    Console.WriteLine("系统不存在网关gatewayCode:" + model_GateWay.gatewayCode);
                    new DBIotSystemLogError().addSystemLogError("", "网关未登记到数据表", "gatewayCode:" + model_GateWay.gatewayCode + " gatewayCode:" + model_GateWay.gatewayCode);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("getHostServerDevice error " + ex);
            }
        }

        /// <summary>
        /// 系统更新状态返回
        /// </summary>
        /// <param name="status"></param>
        /// <param name="msg"></param>
        /// <param name="upgradeRespApiModel"></param>
        public void callBack_softWareUpdateChangeStatus(int status, string msg, UpgradeSoftWareModel upgradeRespApiModel)
        {
            string sql = "update  iot_device_software set sw_status=" + status + ",sw_mod_time='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "',sw_return_msg='" + msg + "' where sw_guid='" + upgradeRespApiModel.guid + "' and sw_status=1 ";
            MySqlYihongIot.ExecuteCommand(sql);

        }
        /// <summary>
        /// 执行指令结果
        /// </summary>
        /// <param name="status"></param>
        /// <param name="msg"></param>
        /// <param name="mQSystemCommand"></param>
        public void callBack_doCommandStatus(int status, string msg, MQSystemCommand mQSystemCommand)
        {
            string sql = "update iot_device_minimachinecommand_log set c_status=2,c_return_code=" + status + ",c_return_time='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "',c_return_msg='" + msg + "' where c_guid='" + mQSystemCommand.guid + "'  ";
            MySqlYihongIot.ExecuteCommand(sql);
        }


        /// <summary>
        /// 初始化网关主机工作
        /// </summary>
        public void resetMichine(DataTable dt, ModelGateway model_GateWay)
        {
            Thread.Sleep(2000);
            ServiceCloudGateWay_Init init = new ServiceCloudGateWay_Init();
            try
            {
                if (dt.Rows[0]["gw_system_start_code"].ToString() != model_GateWay.systemStartCode)
                {//系统启动时 检测查能力

                    //发送测试mq到网关(由于网关的MQ没有生成通道channelpay的能力，这里也有创建通道的作用）
                    init.sendTest(model_GateWay.gatewayCode);

                    //发送传感器采集初始化  能力范围到边缘网关
                    init.resetGpioState(model_GateWay.gatewayDeviceGuid);
                    init.resetDeviceLiveState(model_GateWay.gatewayDeviceGuid);
                    init.resetRS485RelayState(model_GateWay.gatewayDeviceGuid);
                    init.deletePlainItemHandle(model_GateWay.gatewayDeviceGuid);//清空流程
                    init.deleteconditionItemHandle(model_GateWay.gatewayDeviceGuid);//清空条件

                    new ServiceCloudDefaultAutoRun().resetDeviceTaskDefaultRun(model_GateWay.gwGuid);//开始启动的设备

                }
                else
                {
                    init.resetDeviceErrorLiveState(model_GateWay.gatewayDeviceGuid);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(" resetMichine Exception " + ex);
            }


        }


    }
}
